"""
Storage 模块 - 文件关联业务服务
"""
from typing import List, Dict, Any
from axiom_boot.database.base_service import BaseService
from axiom_boot.database import transactional
from axiom_boot.di import service, autowired
from axiom_boot.logging.setup import get_logger
from ..mapper.sys_file_business_relation_mapper import SysFileBusinessRelationMapper
from ..models.sys_file_business_relation import SysFileBusinessRelation

logger = get_logger(__name__)


@service()
class FileRelationService(BaseService[SysFileBusinessRelation, SysFileBusinessRelationMapper]):
    """文件关联业务服务 - 管理业务数据与文件的关联关系"""
    
    def __init__(self, mapper: SysFileBusinessRelationMapper = autowired()):
        super().__init__(mapper)
    
    @transactional
    async def batch_save_file_relations(self, relations_data: List[Dict[str, Any]]) -> bool:
        """批量保存文件关联数据"""
        if not relations_data:
            return True
        
        relations = []
        for data in relations_data:
            relation = SysFileBusinessRelation()
            for key, value in data.items():
                if hasattr(relation, key):
                    setattr(relation, key, value)
            relations.append(relation)
        
        result = await self.batch_save(relations)
        logger.info(f"批量保存文件关联: {len(relations)} 条记录")
        return result
    
    @transactional
    async def create_relation(self, business_type: str, business_id: int, 
                            file_storage_id: int, relation_type: str,
                            sort_order: int = 0, is_primary: bool = False,
                            file_category: str = None) -> SysFileBusinessRelation:
        """
        创建单个文件关联
        
        Args:
            business_type: 业务类型 (如: picknbuy24)
            business_id: 业务ID (车辆表的主键ID)
            file_storage_id: 文件存储ID
            relation_type: 关联类型 (如: image)
            sort_order: 排序序号
            is_primary: 是否主图
            file_category: 文件分类
            
        Returns:
            创建的关联对象
        """
        relation = SysFileBusinessRelation()
        relation.business_type = business_type
        relation.business_id = business_id  # BIGINT类型
        relation.file_id = file_storage_id
        relation.relation_type = relation_type
        relation.sort_order = sort_order
        relation.is_primary = 1 if is_primary else 0
        relation.file_category = file_category
        
        result = await self.save(relation)
        logger.info(f"创建文件关联: {business_type}-{business_id} -> {file_storage_id}")
        return result

